import deliveryApi from '../../service/deliveryApi'
import couponApi from '../../service/couponApi'
import giftApi from '../../service/giftApi'
const app = getApp()
let codeConfig = {...app.globalData.codeConfig}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    picBaseUrl: app.globalData.picBaseUrl,
    // tabs
    currentCoupon: '0',// 卡券属性（0-未使用 1-已使用 2-已过期）
    preferentialTabs: [
      {
        key: '0',
        title: '未使用',
      },
      {
        key: '1',
        title: '已使用',
      },
      {
        key: '2',
        title: '已过期',
      },
    ],
    couponList: [], // 未使用
    couponListUsed: [], // 已使用
    couponListOverTime: [], // 已过期
    loadTips: '上拉加载',
    upAbled: true, // 是否能上拉加载
    page: {
      startPage: 1,
      pageSize: 15,
    },
    loading: false,
    defaultShow: false, // 缺省页
    // 赠送弹窗
    sendGiftType: '1',
    sendPopUpFlag: false,
    giftId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!!options.currentCoupon) {
      this.setData({
        currentCoupon: options.currentCoupon,
      })
    }
    if (options.receiveGift) {
      wx.showToast({
        title: options.receiveGift
      })
    }
    if (app.globalData.receiveCouponStatus !== '') {
      let e = { 
        detail: {
          key: '2'
        }
      }
      app.globalData.receiveCouponStatus ? e.detail.key = '2' : e.detail.key = '0'
      app.globalData.receiveCouponStatus = ''
      this.onChangeCoupon(e)
    } else {
      this.getCouponDiscounts()
    }
  },

  // 优惠券tab
  onChangeCoupon(e) {
    this.setData({
      currentCoupon: e.detail.key,
      'page.startPage': 1,
      upAbled: true, // 是否能上拉加载
    })
    this.getCouponDiscounts(e.detail.key)
  },

  // 获取优惠券
  getCouponDiscounts(currentCoupon = '0') {
    let that = this
    let params = { 
      ...that.data.page, 
      couponStatus: currentCoupon //卡券属性（0-未使用 1-已使用 2-已过期）
    }
    if (that.data.page.startPage === 1) {
      that.setData({
        couponList: [],
        couponListUsed: [],
        couponListOverTime: [],
        loading: true,
        loadTips: '上拉加载', // 上拉加载
        defaultShow: false
      })
    }
    couponApi.couponDiscounts(params).then(res => {
      wx.stopPullDownRefresh()
      if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        if (that.data.page.startPage === 1) {
          that.setData({
            couponList: [],
            couponListUsed: [],
            couponListOverTime: [],
          })
        }
        if (currentCoupon === '0') {
          let list = that.data.couponList.concat(res.data.data.couponList)
          that.setData({
            loading: false,
            couponList: list
          })
          if (that.data.couponList.length === 0) {
            that.setData({
              defaultShow: true,
              upAbled: false
            })
          } else {
            that.setData({
              defaultShow: false
            })
          }
          if (res.data.data.couponList.length < that.data.page.pageSize) {
            that.setData({
              loadTips: '暂无更多数据',
              upAbled: false
            })
          } else {
            that.setData({
              loadTips: '上拉加载'
            })
          }
        } else if (currentCoupon === '1') {
          let list = that.data.couponListUsed.concat(res.data.data.couponList)
          that.setData({
            loading: false,
            couponListUsed: list
          })
          if (that.data.couponListUsed.length === 0) {
            that.setData({
              defaultShow: true,
              upAbled: false
            })
          } else {
            that.setData({
              defaultShow: false
            })
          }
          if (res.data.data.couponList.length < that.data.page.pageSize) {
            that.setData({
              loadTips: '暂无更多数据',
              upAbled: false
            })
          } else {
            that.setData({
              loadTips: '上拉加载'
            })
          }
        } else if (currentCoupon === '2') {
          let list = that.data.couponListOverTime.concat(res.data.data.couponList)
          that.setData({
            loading: false,
            couponListOverTime: list
          })
          if (that.data.couponListOverTime.length === 0) {
            that.setData({
              defaultShow: true,
              upAbled: false
            })
          } else {
            that.setData({
              defaultShow: false
            })
          }
          if (res.data.data.couponList.length < that.data.page.pageSize) {
            that.setData({
              loadTips: '暂无更多数据',
              upAbled: false
            })
          } else {
            that.setData({
              loadTips: '上拉加载'
            })
          }
        }
      } else {
        that.setData({
          loading: false
        })
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }).catch(res => {
      console.log(res);
    })
  },

  // 立即使用
  onNowUse() {
    wx.switchTab({
      url: '../index/index'
    })
  },

	// 赠送
	onSend(e) {
		let item = e.currentTarget.dataset.item
		let params = {
			couponId: item.couponId,
			couponType: item.couponType
    }
    wx.showLoading({
      title: '加载中'
    })
		couponApi.getCouponBalance(params).then(res => {
      wx.hideLoading()
			if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
				if (res.data.data.balance === '0') {
					wx.showToast({
						title: '系统正在处理您的请求，请稍候',
						icon: 'none'
					})
				} else {
					item.count = res.data.data.balance
					app.globalData.sendGiftData = item
					this.setData({
            sendPopUpFlag: true,
            sendGiftType: e.currentTarget.dataset.gifttype
					})
				}
			}
		})
	},
  
  // 关闭赠送弹窗
  onCloseSendPopUp() {
    this.setData({
      sendPopUpFlag: false
    })
  },

  // 赠送给微信好友
  onSendFriend() {
    this.onCloseSendPopUp()
    wx.navigateTo({
      url: `../sendGiftToFriend/sendGiftToFriend?sendGiftType=${this.data.sendGiftType}`
    })
  },
  
  // 赠送给BU地址
  onSendBlockChainAddress() {
    wx.navigateTo({
      url: `../sendGiftToBUAddress/sendGiftToBUAddress?sendGiftType=${this.data.sendGiftType}`
    })
    this.onCloseSendPopUp()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let sendGiftOverBackData = app.globalData.sendGiftOverBackData
    if (sendGiftOverBackData) {
      this.setData({
        currentCoupon: '0',
        'page.startPage': 1,
        upAbled: true, // 是否能上拉加载
      })
      this.getCouponDiscounts('0')
      wx.showToast({
        title: sendGiftOverBackData
      })
      app.globalData.sendGiftOverBackData = ''
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      'page.startPage': 1,
      upAbled: true, // 是否可上拉加载
    })
    let e = {
      detail: {
        key: this.data.currentCoupon
      }
    }
    this.onChangeCoupon(e)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.upAbled) {
      this.setData({
        'page.startPage': this.data.page.startPage + 1,
        loadTips: '加载中...',
      })
      this.getCouponDiscounts(this.data.currentCoupon)
    }
  }
})